package org.amos.msg.platform.wx;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.amos.core.basic.utils.JsonUtils;
import org.amos.msg.model.WxMiniAppContentModel;
import org.amos.msg.params.PushMsgParam;
import org.amos.msg.platform.AbstractMsgPlatform;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
public class WxMiniAppMsgPlatform extends AbstractMsgPlatform<WxMiniAppMsgConfig> {

    private WxMaService client;

    public WxMiniAppMsgPlatform(String id, WxMiniAppMsgConfig config) {
        super(id, config);
    }

    @Override
    protected void initClient() {
        client = new WxMaServiceImpl();
        WxMaDefaultConfigImpl wxMaDefaultConfig = new WxMaDefaultConfigImpl();
        wxMaDefaultConfig.setAppid(config.getAppId());
        wxMaDefaultConfig.setSecret(config.getAppSecret());
        client.setWxMaConfig(wxMaDefaultConfig);
    }

    @Override
    public Boolean push(PushMsgParam param) {
        WxMiniAppContentModel contentModel = (WxMiniAppContentModel) param.getContentModel();
        List<WxMaSubscribeMessage> wxMaSubscribeMessages = assembleReq(param.getReceiver(), contentModel);
        for (WxMaSubscribeMessage message : wxMaSubscribeMessages) {
            try {
                client.getSubscribeService().sendSubscribeMsg(message);
            } catch (Exception e) {
                log.info("MiniProgramAccountHandler#handler fail! param:{},e:{}", JsonUtils.objectToJson(param), Throwables.getStackTraceAsString(e));
            }
        }
        return Boolean.TRUE;
    }

    /**
     * 组装发送模板信息参数
     */
    private List<WxMaSubscribeMessage> assembleReq(Set<String> receiver, WxMiniAppContentModel contentModel) {
        List<WxMaSubscribeMessage> messageList = new ArrayList<>(receiver.size());
        for (String openId : receiver) {
            WxMaSubscribeMessage subscribeMessage = WxMaSubscribeMessage.builder()
                    .toUser(openId)
                    .data(getWxMaTemplateData(contentModel.getMiniProgramParam()))
                    .templateId(contentModel.getTemplateId())
                    .page(contentModel.getPage())
                    .build();
            messageList.add(subscribeMessage);
        }
        return messageList;
    }

    /**
     * 构建订阅消息参数
     *
     * @returnp
     */
    private List<WxMaSubscribeMessage.MsgData> getWxMaTemplateData(Map<String, String> data) {
        List<WxMaSubscribeMessage.MsgData> templateDataList = new ArrayList<>(data.size());
        data.forEach((k, v) -> templateDataList.add(new WxMaSubscribeMessage.MsgData(k, v)));
        return templateDataList;
    }
}
